import React, { useState } from "react";
import { Button, Input, PopConfirm } from "tea-component";
import { AvatarWithProfile } from "../../../components/avatarWithProfile";

import { addFriendsToBlackList, deleteFriend } from '../../../api';
import { useMessageDirect } from "../../../utils/react-use/useDirectMsgPage";
import "./friend-list.scss";
import { ConfirmDialog, ConfirmDialogRecordsType } from "../../message/groupSetting/ConfirmDialog";
import { useDialogRef } from "../../../utils/react-use/useDialog";
import timRenderInstance from "../../../utils/timRenderInstance";
import { ModifyFriendProfileParams } from "im_electron_sdk/dist/interfaces";

export const ListItem = (props: {
  userId: string;userName: string;friendProfile: State.userProfile;remark:string;
  onRefresh: () => Promise<any>;}) => {
  const { userId, userName,remark, onRefresh, friendProfile } = props;
  const { user_profile_face_url, user_profile_role, user_profile_nick_name, user_profile_add_permission, user_profile_identifier, user_profile_gender, user_profile_self_signature } = friendProfile;
  const directToMsgPage = useMessageDirect();
  const [showBtn,setShowBtn] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [input, setInput] = useState(remark||userName);
  const [showName,setshowName] = useState(remark||userName)
  const dialogRef = useDialogRef<ConfirmDialogRecordsType>();
  const handleDelete = async (close: () => any) => {
    try {
      await deleteFriend(userId);
      close();
      onRefresh();
    } catch (e) {
      console.log(e);
    }
  };


    const profile = {
      userId: user_profile_identifier,
      nickName: user_profile_nick_name,
      faceUrl: user_profile_face_url,
      gender: user_profile_gender,
      signature: user_profile_self_signature,
      role: user_profile_role,
      addPermission: user_profile_add_permission
  }

  const addToBlackList = async (close) => {
    try {
      await addFriendsToBlackList([userId]);
      close();
      onRefresh();
    } catch (e) {
      console.log(e)
    }
  }
  const handleModify = async () => {
    let param : ModifyFriendProfileParams = {
      params: {
          friendship_modify_friend_profile_param_identifier: user_profile_identifier, 
          friendship_modify_friend_profile_param_item: {
            friend_profile_item_remark: input,    //选填
        }    //选填
      },
    }
  
  const {code} = await timRenderInstance.TIMFriendshipModifyFriendProfile(param);
  if(code == 0){
      // 成功
      setshowName(input);
  }
    if (code === 0) {
        // let selfPro = selfUserInfo as any;
        // selfPro.nickName = input;
        // setSelfUserInfo(selfPro);
        // dispatch(setUserInfo(selfPro));
    }

};
  function handleInput() {
    dialogRef.current.open({
      description: `是否将备注修改为`,
      modifyContent: input,
      onConfirm: handleModify,
    });
}
  const toMessage = ()=>{
    directToMsgPage({
      convType: 1,
      profile: friendProfile,
    });
  }
  return (
    <div className="friend-list--content__item" >
      <div className="item-left" onClick={toMessage}>
        <div className="item-left__avatar">
          <AvatarWithProfile profile={profile} />
        </div>
        <div className="item-left__info">
          <span className="item-left__info--name">{showName}</span>
          {/* <span className="item-left__info--dep">{depName}</span> */}
        </div>
      </div>
      {showBtn?      
      <div className="item-right">
        {isEdit && (
          <Input style={{width:"150px"}}  className="group-introduction--input"  size="full"  placeholder="输入备注后按回车"  value={input}
              onChange={(value) => {
                  setInput(value);
              }}
              onBlur={handleInput}
              onKeyDown={(e) => {
                  if (e.key === "Enter") {
                      handleInput();
                  }
              }}
          />
          )}
        <Button type="link" onClick={(e) => { e.stopPropagation();  setIsEdit(!isEdit);} } >好友备注</Button>
        <PopConfirm  title="确认要删除该好友吗?"  footer={(close) => (
            <>
              <Button type="link" onClick={(e) => { e.stopPropagation();  handleDelete(close);} }>
                确认
              </Button>
              <Button type="text" onClick={close}> 取消 </Button>
            </>
          )}
        >
          <Button type="link" className="item-right__btn"> 删除</Button>
        </PopConfirm>
        <PopConfirm  title="确认要将该好友加入到黑名单吗?"  footer={(close) => (
            <>
              <Button type="link" onClick={(e) => {  e.stopPropagation();  addToBlackList(close);}}>
                确认
              </Button>
              <Button type="text" onClick={close}>取消</Button>
            </>
          )}
        >
          <Button type="link" className="item-right__btn">
            加入黑名单
          </Button>
        </PopConfirm>
      </div>
      :<Button type="link" className="item-right__btn" onClick={()=>setShowBtn(true)}>...</Button>}
        <ConfirmDialog  dialogRef={dialogRef}  onSuccess={() => {
            setIsEdit(false);
            }}
        />
    </div>
  );
};
